package com.selftest.web.filter;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.PropertyPreFilter;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.selftest.web.annotation.ResponseJSON;

import java.util.Objects;

/**
 * 实现对象属性序列化 filter
 */
public class EntityClassPropertyFilter implements PropertyPreFilter {

    private SerializeFilter filter;
    private ResponseJSON annotation;

    /**
     * 实例化
     * @param filter
     * @param annotation
     */
    public EntityClassPropertyFilter(SerializeFilter filter, ResponseJSON annotation) {
        this.filter = filter;
        this.annotation = annotation;
    }

    /**
     * 自定义过滤规则, 判断哪些属性需要被序列化，哪些属性需要被过滤掉
     * @param jsonSerializer
     * @param object
     * @param name
     * @return
     */
    @Override
    public boolean apply(JSONSerializer jsonSerializer, Object object, String name) {
        Class<?> elementType = object.getClass();
        if (Objects.nonNull(elementType)) {
            while (!elementType.equals(Object.class)) {
                if (Objects.nonNull(filter) && filter instanceof PropertyPreFilter) {
                    // 这里调用的是 JSONHttpMessageConverter 中 getSerializeFilter() 提供的 SerializeFilter
                    if (!((PropertyPreFilter)filter).apply(jsonSerializer, object, name)) {
                        return false;
                    }
                }
                elementType = elementType.getSuperclass();
            }
        }
        return true;
    }
}
